# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name:         sfp_malwarepatrol
# Purpose:      SpiderFoot plug-in to search MalwarePatrol's daatabase for
#               potential malicious IPs/hostnames.
#
# Author:      Steve Micallef <steve@binarypool.com>
#
# Created:     25/07/2016
# Copyright:   (c) Steve Micallef 2016
# Licence:     GPL
# -------------------------------------------------------------------------------

from spiderfoot import SpiderFootEvent, SpiderFootPlugin


class sfp_malwarepatrol(SpiderFootPlugin):

    meta = {
        'name': "MalwarePatrol",
        'summary': "Searches malwarepatrol.net's database of malicious URLs/IPs.",
        'flags': ["apikey"],
        'useCases': ["Investigate", "Passive"],
        'categories': ["Reputation Systems"],
        'dataSource': {
            'website': "https://www.malwarepatrol.net/",
            'model': "FREE_AUTH_LIMITED",
            'references': [
                "https://www.malwarepatrol.net/tech-support/",
                "https://www.malwarepatrol.net/integrations-formats-tip-siem-soar/",
                "https://www.malwarepatrol.net/community-contribution-suspicious-emails/",
                "https://www.malwarepatrol.net/non-commercial/#lists"
            ],
            'apiKeyInstructions': [
                "Visit https://www.malwarepatrol.net/free-guard-block-list/",
                "Register a free account",
                "The Password/Receipt number will be mailed to your email"
            ],
            'favIcon': "https://www.malwarepatrol.net/wp-content/uploads/2020/02/rsz_12logo-150x150.png",
            'logo': "https://www.malwarepatrol.net/wp-content/uploads/2016/06/rsz_mp_logo_clear_-_small.png",
            'description': "Based in the USA and Brazil, our history is one of community spirit and dedication to "
            "Internet security that began in 2005 when a group started sharing malicious links using a simple mailing list.\n"
            "Collecting, analyzing, and sharing data for over a decade has allowed us "
            "to develop an extensive network of sensors, sharing agreements, and community contributors. "
            "The result is our vast database of unique and historically rich – “intelligent” – threat data.",
        }
    }

    opts = {
        "api_key": "",
        'checkaffiliates': True,
        'checkcohosts': True,
    }

    optdescs = {
        "api_key": "Malwarepatrol.com 'receipt' ID, provided once signing up for their open-source feed. Without this you cannot obtain their feed.",
        'checkaffiliates': "Apply checks to affiliates?",
        'checkcohosts': "Apply checks to sites found to be co-hosted on the target's IP?",
    }

    results = None
    errorState = False

    def setup(self, sfc, userOpts=dict()):
        self.sf = sfc
        self.results = self.tempStorage()

        for opt in list(userOpts.keys()):
            self.opts[opt] = userOpts[opt]

    def watchedEvents(self):
        return [
            "INTERNET_NAME",
            "AFFILIATE_INTERNET_NAME",
            "IP_ADDRESS",
            "AFFILIATE_IPADDR",
            "CO_HOSTED_SITE",
        ]

    def producedEvents(self):
        return [
            "BLACKLISTED_IPADDR",
            "BLACKLISTED_AFFILIATE_IPADDR",
            "BLACKLISTED_INTERNET_NAME",
            "BLACKLISTED_AFFILIATE_INTERNET_NAME",
            "BLACKLISTED_COHOST",
            "MALICIOUS_IPADDR",
            "MALICIOUS_AFFILIATE_IPADDR",
            "MALICIOUS_INTERNET_NAME",
            "MALICIOUS_AFFILIATE_INTERNET_NAME",
            "MALICIOUS_COHOST",
        ]

    def queryAddr(self, qaddr):
        data = dict()
        url = "http://lists.malwarepatrol.net/cgi/getfile?receipt=" + \
              self.opts['api_key'] + "&product=8&list=smoothwall"

        data['content'] = self.sf.cacheGet("sfmalwarepatrol", 72)
        if data['content'] is None:
            data = self.sf.fetchUrl(url, useragent=self.opts['_useragent'])
            if data['content'] is None:
                self.error("Unable to fetch " + url)
                return None
            self.sf.cachePut("sfmalwarepatrol", data['content'])

        for line in data['content'].split('\n'):
            if len(line) < 2 or line.startswith('#'):
                continue

            if line.startswith(qaddr):
                return True

        return False

    def handleEvent(self, event):
        eventName = event.eventType
        eventData = event.data

        if self.errorState:
            return

        self.debug(f"Received event, {eventName}, from {event.module}")

        if not self.opts['api_key']:
            self.error("You enabled sfp_malwarepatrol but did not provide a receipt ID!")
            self.errorState = True
            return

        if eventData in self.results:
            self.debug(f"Skipping {eventData} as already searched.")
            return

        self.results[eventData] = True

        if eventName == 'IP_ADDRESS':
            malicious_type = "MALICIOUS_IPADDR"
            blacklist_type = "BLACKLISTED_IPADDR"
        elif eventName == 'AFFILIATE_IPADDR':
            if not self.opts.get('checkaffiliates', False):
                return
            malicious_type = "MALICIOUS_AFFILIATE_IPADDR"
            blacklist_type = "BLACKLISTED_AFFILIATE_IPADDR"
        elif eventName == "INTERNET_NAME":
            malicious_type = "MALICIOUS_INTERNET_NAME"
            blacklist_type = "BLACKLISTED_INTERNET_NAME"
        elif eventName == "AFFILIATE_INTERNET_NAME":
            if not self.opts.get('checkaffiliates', False):
                return
            malicious_type = "MALICIOUS_AFFILIATE_INTERNET_NAME"
            blacklist_type = "BLACKLISTED_AFFILIATE_INTERNET_NAME"
        elif eventName == "CO_HOSTED_SITE":
            if not self.opts.get('checkcohosts', False):
                return
            malicious_type = "MALICIOUS_COHOST"
            blacklist_type = "BLACKLISTED_COHOST"
        else:
            self.debug(f"Unexpected event type {eventName}, skipping")
            return

        if not self.queryAddr(eventData):
            return

        text = f"MalwarePatrol [{eventData}]"

        evt = SpiderFootEvent(malicious_type, text, self.__name__, event)
        self.notifyListeners(evt)

        evt = SpiderFootEvent(blacklist_type, text, self.__name__, event)
        self.notifyListeners(evt)

# End of sfp_malwarepatrol class
